﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PPIDesktopClient.General;
using PPIDesktopClient.Entities;
using PPIMobileInterface.Logic;
using PPIMobileInterface.Entities;
using PPIDesktopClient.Logic;
using System.IO;
using System.Configuration;
using System.Threading;
using VMind.Global;

namespace PPIDesktopClient.Controls
{
    public partial class UploaderImages : UserControl
    {

        #region Fields
        private string m_mobiledatabasePath;
        private List<EVendor_Visit_XMissionStructure> m_VendorVisits;
        private List<EVendor_Visit_XMissionStructures_Image> m_ImagesUpload;
        private int m_TotalData = 0;
        private bool m_Stopped = false;
        private bool m_Finished = false;
        #endregion Private Properties

        #region Properties

        public string MobileDatabasePath
        {
            get { return m_mobiledatabasePath; }
            set { m_mobiledatabasePath = value; }
        }
        
        #endregion

        #region Constructor

        public UploaderImages()
        {
            InitializeComponent();
            HideShowControls(false);
        }

        #endregion

        #region Public Methods

        public void Start()
        {
            if (!m_BackgroundWorker.IsBusy)
            {
                m_Finished = false;
                m_BackgroundWorker.RunWorkerAsync();
            
            }
        }

        private void WaitFiveMinutes()
        {
            System.Threading.Thread.Sleep(300000);
        }

        public void Stop()
        {
            m_BackgroundWorker.CancelAsync();
            m_Stopped = !m_Stopped;
            if(m_Stopped)
                this.btnStop.Image = global::PPIDesktopClient.Properties.Resources.Play;
            else
                this.btnStop.Image = global::PPIDesktopClient.Properties.Resources.Stop;
        }

        #endregion

        #region Private Methods

        private void UploadImages(DoWorkEventArgs e)
        {
            try
            {
                HideShowControls(true);
                LoadImages();
                //CalculateTotalData();
                m_TotalData = m_ImagesUpload.Count;

                Int32 _CountUploaded = m_TotalData;
                Int32 _ImageServerID;
                DirectoryInfo _ImagesDirectory = GetImagesDirectory();
                string _FullPathImage = "";

                foreach (EVendor_Visit_XMissionStructures_Image  i in m_ImagesUpload)
                {

                    _FullPathImage = _ImagesDirectory.FullName + Path.DirectorySeparatorChar + i.FileName;
                    //VendorImage.Filename = _ImagesDirectory.FullName + Path.DirectorySeparatorChar + VendorImage.Filename;
                    if (File.Exists(_FullPathImage))
                    {
                        i.FileName = i.Asset.Id + "_" + i.Id+ ".jpeg";
                        _ImageServerID = LVendor_Visit_XMissionStructures_Image.UploadImage(i, _FullPathImage);
                        //i.Vendor_Visit_XMissionStructures_ImageId = Int32.MinValue;
                        //i.Filename = _FullPathImage;
                        //_ImageServerID = LVendor_Visit_XMissionStructures_Image.Save(i);
                        LogicLayer.UpdateImageServerID(_ImageServerID, i.Id, MobileDatabasePath);
                        _CountUploaded--;
                        m_BackgroundWorker.ReportProgress(ReportProgress(_CountUploaded));
                        System.Threading.Thread.Sleep(ConvertHelper.ToInt32(ConfigurationManager.AppSettings["TimeWaitUpImages"]));
                    }

                }

                //foreach (EVendor_Visit_XMissionStructure Visit in m_VendorVisits)
                //{
                //    if (m_BackgroundWorker.CancellationPending)
                //    {
                //        e.Cancel = true;
                //        return;
                //    }
                //    foreach (EVendor_Visit_XMissionStructures_Pole Pole in Visit.Poles)
                //    {
                //        if (m_BackgroundWorker.CancellationPending)
                //        {
                //            e.Cancel = true;
                //            return;
                //        }
                //        foreach (EVendor_Visit_XMissionStructures_Image VendorImage in Pole.Vendor_Visit_XMissionStructures_Images)
                //        {
                //            if (m_BackgroundWorker.CancellationPending)
                //            {
                //                e.Cancel = true;
                //                return;
                //            }
                //            _FullPathImage = _ImagesDirectory.FullName + Path.DirectorySeparatorChar + VendorImage.Filename;
                //            //VendorImage.Filename = _ImagesDirectory.FullName + Path.DirectorySeparatorChar + VendorImage.Filename;
                //            if (File.Exists(_FullPathImage))
                //            {
                //                VendorImage.Filename = VendorImage.StructureServerID + "_" + VendorImage.Vendor_Visit_XMissionStructures_ImageId + ".jpeg";
                //                _ImageServerID = PPIProxy.WebServiceConsumer.UploadImage(VendorImage, _FullPathImage);
                //                LogicLayer.UpdateImageServerID(_ImageServerID, VendorImage.Vendor_Visit_XMissionStructures_ImageId, MobileDatabasePath);
                //                _CountUploaded--;
                //                m_BackgroundWorker.ReportProgress(ReportProgress(_CountUploaded));
                //                System.Threading.Thread.Sleep(ConvertHelper.ToInt32(ConfigurationManager.AppSettings["TimeWaitUpImages"]));
                //            }
                //        }
                //    }
                //    foreach (EVendor_Visit_XMissionStructures_Image VendorImage in Visit.Images)
                //    {
                //        if (m_BackgroundWorker.CancellationPending)
                //        {
                //            e.Cancel = true;
                //            return;
                //        }
                //        _FullPathImage = _ImagesDirectory.FullName + Path.DirectorySeparatorChar + VendorImage.Filename;
                //        //VendorImage.Filename = _ImagesDirectory.FullName + Path.DirectorySeparatorChar + VendorImage.Filename;
                //        if (File.Exists(_FullPathImage))
                //        {
                //            VendorImage.Filename = VendorImage.StructureServerID + "_" + VendorImage.Vendor_Visit_XMissionStructures_ImageId + ".jpeg";
                //            _ImageServerID = PPIProxy.WebServiceConsumer.UploadImage(VendorImage, _FullPathImage);
                //            LogicLayer.UpdateImageServerID(_ImageServerID, VendorImage.Vendor_Visit_XMissionStructures_ImageId, MobileDatabasePath);
                //            _CountUploaded--;
                //            m_BackgroundWorker.ReportProgress(ReportProgress(_CountUploaded));
                //            System.Threading.Thread.Sleep(ConvertHelper.ToInt32(ConfigurationManager.AppSettings["TimeWaitUpImages"]));
                //        }
                //    }
                //}
            }
            catch (Exception ex)
            {
                ErrorManager.Log("Exception", "UploadImages " + ex.TargetSite, ex.Message, ex.StackTrace);
            }
        }

        private DirectoryInfo GetImagesDirectory()
        {
            DirectoryInfo _MobileDatabaseDirectory = new DirectoryInfo(Path.GetDirectoryName(MobileDatabasePath));
            DirectoryInfo[] _Directories = _MobileDatabaseDirectory.GetDirectories();
            return _Directories[0];
        }

        private void CalculateTotalData()
        {
            foreach (EVendor_Visit_XMissionStructure Visit in m_VendorVisits)
            {
                foreach (EVendor_Visit_XMissionStructures_Pole Pole in Visit.Poles)
                {
                    m_TotalData += Pole.Images.Count;
                }
                m_TotalData += Visit.Images.Count;
            }

        }

        private void LoadImages()
        {
            //List<EVisit> _MobileVisits = LogicLayer.LoadAllCompleteVisits(m_mobiledatabasePath, false);
            //m_VendorVisits = LVendor_Visit_XMissionStructure.GetListFromMobileVisits(_MobileVisits);

            List<EImage> _MobileImages = LogicLayer.SelectImages(m_mobiledatabasePath, false);
            m_ImagesUpload = LVendor_Visit_XMissionStructures_Image.GetImagesFromMobileImages(_MobileImages);
        }

        private int ReportProgress(int _CountUploaded)
        {
            int _Progress;
            try
            {
                _Progress = ((m_TotalData - _CountUploaded) * 100) / m_TotalData;
            }
            catch (Exception)
            {
                _Progress = 0;
            }
            return _Progress;
        }

        private delegate void HideShowControlsCallback(bool status);

        private void HideShowControls(bool status)
        {
            if (this.InvokeRequired)
            {
                HideShowControlsCallback d = new HideShowControlsCallback(HideShowControls);
                this.Invoke(d, new object[] { status });
            }
            else
            {
                foreach (Control c in this.Controls)
                {
                    c.Visible = status;
                }
            }
        }

        private void CopyDirectories()
        {
            DirectoryInfo _DirectorySource = null;
            try
            {
                string _DirectoryName = Path.GetDirectoryName(MobileDatabasePath);
                _DirectorySource = new DirectoryInfo(_DirectoryName);
                DirectoryInfo _DirectoryDestination = new DirectoryInfo(Constants.K_SentPath);
                DirHelper.isDirectory(_DirectoryDestination.FullName + Path.DirectorySeparatorChar + _DirectorySource.Name);
                _DirectoryDestination = new DirectoryInfo(_DirectoryDestination.FullName + Path.DirectorySeparatorChar + _DirectorySource.Name);
                DirHelper.CopyFiles(_DirectorySource, _DirectoryDestination, true);
            }
            catch (IOException ioex)
            {
                ErrorManager.Log("IOException", "UploaderImages.CopyDirectories " + ioex.TargetSite, ioex.Message, ioex.StackTrace);
            }
            catch (System.Security.SecurityException secex)
            {
                ErrorManager.Log("System.Security.SecurityException", "UploaderImages.CopyDirectories " + secex.TargetSite, secex.Message, secex.StackTrace);
            }
            finally
            {
                //Clean directory
                _DirectorySource.Delete(true);
            }
        }

        #endregion

        #region Events
        private void m_BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                while (!m_Stopped && !m_Finished)
                {
                    BackgroundWorker bw = (BackgroundWorker)sender;
                    if (bw.CancellationPending)
                    {
                        e.Cancel = true;
                    }
                    if (XMLHelper.HastNextImageNode(Constants.K_XmlOutboxPath))
                    {
                        MobileDatabasePath = XMLHelper.GetNextImageNode(Constants.K_XmlOutboxPath);
                        UploadImages(e);
                        m_Finished = true;

                    }
                    else
                    {
                        Thread.Sleep(10000);
                    }

                    //WaitFiveMinutes();
                }
                //m_BackgroundWorker.CancelAsync();

            }
            catch (Exception ex)
            {
                ErrorManager.Log("Exception", "m_BackgroundWorker_DoWork " + ex.TargetSite, ex.Message, ex.StackTrace);
            }
        }

        private void m_BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            int countUploaded = (((((e.ProgressPercentage * m_TotalData) / 100) - m_TotalData) * -1) - m_TotalData) * -1;
            if (countUploaded != m_TotalData)
                countUploaded++;
            lblShowStats.Text = (countUploaded) + " / " + m_TotalData.ToString();
            progressBarX1.Value = e.ProgressPercentage;
        }


        /// <summary>
        /// Gabriel Barzola
        /// 30/05/2008
        /// 1.Verifica si hay nuevas imagenes a subir
        /// 2.Actualiza el estado del XML 
        /// 3.Copia los directorios completados a la carpeta SENT
        /// 4.Oculta el control en caso de que este terminado
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void m_BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                progressBarX1.Value = 0;
                m_TotalData = 0;
                lblShowStats.Text = "";
                if (!e.Cancelled)
                {
                    if (MobileDatabasePath != null)
                    {
                        string[] _NameFolder = MobileDatabasePath.Split(Path.DirectorySeparatorChar);
                        string _IDFolder = _NameFolder[_NameFolder.Length - 2];
                        XMLHelper.UpdateImageNode(Constants.K_XmlOutboxPath, _IDFolder);
                        CopyDirectories();

                    }
                    if (XMLHelper.HastNextImageNode(Constants.K_XmlOutboxPath) && !m_BackgroundWorker.IsBusy)
                    {
                        MobileDatabasePath = XMLHelper.GetNextImageNode(Constants.K_XmlOutboxPath);
                        m_BackgroundWorker.RunWorkerAsync();
                        m_Finished = false;
                    }
                    else
                    {
                        HideShowControls(false);
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorManager.Log("Exception", "m_BackgroundWorker_RunWorkerCompleted " + ex.TargetSite, ex.Message, ex.StackTrace);
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            Stop();
        }

        #endregion

        
    }
}
